// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'timemechine-6gk33n8ja79a3c4a'
})

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  let date = new Date()
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month < 10 ? ('0' + month) : month;
  let day = date.getDate();
  day = day < 10 ? ('0' + day) : day;
  let data = year + "-" + month + "-" + day

  //先到用户表取到所有用户openid
  let users = db.collection('user_list').get();
  
  let sendMessage
  for (var i = 0; i < (await users).data.length; i++) {
    sendMessage = db.collection('mission_list').where({
        "_openid": (await users).data[i]._openid,
        "date": data,
        "state": false
      })
      .get();

    if ((await sendMessage).data.length > 0) {
      await cloud.openapi.subscribeMessage.send({
        touser: (await sendMessage).data[0]._openid,
        page: 'pages/login/login',
        lang: 'zh_CN',
        data: {
          thing12: {
            value: (await sendMessage).data[0].mission
          },
          time11: {
            value: (await sendMessage).data[0].date + ' ' + (await sendMessage).data[0].time
          },
          thing10: {
            value: '您有任务未完成，如果已完成，请确认完成！'
          },
        },
        templateId: 'em9B7aike40C2AK0LWNHyEybYI8VjdZa4UIcrzdAo-4',
        miniprogramState: 'developer'
      });
    }
  }
  return (await sendMessage);
}